package com.shiro.demo0929.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @date 2020/10/2 13:23
 */
@Controller
public class LoginController {

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username , String password , Model model){
//        获取当前用户
        Subject subject = SecurityUtils.getSubject();

//        封装用户的登录数据（进行加密）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
//        执行登录的方法（不需要自己去实现，直接调用shiro的方法）
            subject.login(token);
            return "index";
        }catch (UnknownAccountException  e){
//             用户名不存在异常
            model.addAttribute("msg","用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException  e){
//             密码错误异常
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }


    /**
     * 跳转到未授权界面
     * @return
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(){

        return "unauthorized";
    }
}
